package handler

import (
    "encoding/json"
    "fcs-api/src/app/business"
    "fcs-api/src/app/model"
    "fcs-api/src/app/utils"
    "net/http"
    "strconv"
    "strings"

    i18n "git.inspur.com/x/common/i18n"
    "github.com/emicklei/go-restful"
)

func (api *APIHandler) handleGetTemplateList(request *restful.Request, response *restful.Response) {
    logger.Debug("handleGetTemplateList start.")
    var err error
    pageNoStr := request.QueryParameter("pageNo")
    pageSizeStr := request.QueryParameter("pageSize")
    name := request.QueryParameter("name")
    scene := request.QueryParameter("scene")
    runtime := request.QueryParameter("runtime")
    pageNo, pageSize := 0, 0
    if pageNoStr != "" || pageSizeStr != "" {
        pageNo, err = strconv.Atoi(pageNoStr)
        if err != nil {
            handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.metric.log")))
            return
        }
        pageSize, err = strconv.Atoi(pageSizeStr)
        if err != nil {
            handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.template.query_param")))
            return
        }
    }

    tl, err := GetTemplateList()
    if err != nil {
        handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.template.query")))
        return
    }
    logger.Debug("handleGetTemplateList TemplateList len: ", len(tl.Templates))
    _ = response.WriteHeaderAndEntity(http.StatusOK, GetTemplatePage(pageNo, pageSize, name, scene, runtime, tl))
}

func (api *APIHandler) handleGetTemplateScenes(request *restful.Request, response *restful.Response) {
    tl, err := GetTemplateList()
    if err != nil {
        handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.template.detail")))
        return
    }
    logger.Debug("handleGetTemplateScenes TemplateScenes len: ", len(tl.Scenes))
    _ = response.WriteHeaderAndEntity(http.StatusOK, map[string]interface{}{"scenes": tl.Scenes})
}

func GetTemplateList() (*model.TemplateList, error) {
    bucketName := model.Base.OssBucket
    token := utils.GetAdminToken()
    objectKey := "runtime" + "/" + "template.json"
    downloadLink, err := business.GetDownloadLink(model.Base.OssDownloadHost, bucketName, objectKey, "bearer "+token)
    if err != nil {
        return &model.TemplateList{}, err
    }
    b, err := utils.HttpReq(downloadLink, "", http.MethodGet, nil, nil)
    if err != nil {
        return &model.TemplateList{}, err
    }
    tl := &model.TemplateList{}
    err = json.Unmarshal(b, tl)
    if err != nil {
        return &model.TemplateList{}, err
    }
    return tl, nil
}

func GetTemplatePage(pageNo, pageSize int, name, scene, runtime string, tl *model.TemplateList) *model.TemplatePage {
    tmpTsByName := []model.Template{}
    tmpTsByScene := []model.Template{}
    tmpTsByRuntime := []model.Template{}
    tp := &model.TemplatePage{}
    if name != "" {
        for _, t := range tl.Templates {
            if strings.Contains(t.DisplayName, name) {
                tmpTsByName = append(tmpTsByName, t)
            }
        }
    } else {
        tmpTsByName = tl.Templates
    }

    if scene != "" {
        for _, t := range tmpTsByName {
            if t.Scene == scene {
                tmpTsByScene = append(tmpTsByScene, t)
            }
        }
    } else {
        tmpTsByScene = tmpTsByName
    }

    if runtime != "" {
        for _, t := range tmpTsByScene {
            if t.Runtime == runtime {
                tmpTsByRuntime = append(tmpTsByRuntime, t)
            }
        }
    } else {
        tmpTsByRuntime = tmpTsByScene
    }

    if len(tmpTsByRuntime) <= pageSize {
        tp = &model.TemplatePage{
            TotalCount: int64(len(tmpTsByRuntime)),
            PageSize:   pageSize,
            PageNo:     pageNo,
            Data:       tmpTsByRuntime,
        }
    } else {
        start := (pageNo - 1) * pageSize
        end := start + pageSize
        if end > len(tmpTsByRuntime) {
            end = len(tmpTsByRuntime)
        }
        for i := start; i < end; i++ {
            tp.Data = append(tp.Data, tmpTsByRuntime[i])
        }
        tp.PageNo = pageNo
        tp.PageSize = pageSize
        tp.TotalCount = int64(len(tmpTsByRuntime))
    }
    return tp
}
